<template>
  <view class="container">
    <view class="header">
      <text class="title">欢迎注册</text>
      <text class="subtitle">成为会员享受优惠</text>
    </view>
    
    <view class="form">
      <view class="form-item">
        <text class="label">姓名</text>
        <input v-model="name" placeholder="请输入姓名" class="input" />
      </view>
      
      <view class="form-item">
        <text class="label">手机号</text>
        <input v-model="phone" type="number" placeholder="请输入手机号" class="input" />
      </view>
      
      <button type="primary" @click="handleLogin" class="btn">
        微信授权登录
      </button>
    </view>
  </view>
</template>

<script>
import { wechatLogin } from '../../api/auth.js'

export default {
  data() {
    return {
      name: '',
      phone: ''
    }
  },
  
  methods: {
    handleLogin() {
      if (!this.name || !this.phone) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' })
        return
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        uni.showToast({ title: '手机号格式错误', icon: 'none' })
        return
      }
      
      uni.login({
        provider: 'weixin',
        success: async (loginRes) => {
          try {
            uni.showLoading({ title: '登录中...' })
            
            const result = await wechatLogin(loginRes.code, this.phone, this.name)
            
            uni.setStorageSync('token', result.access_token)
            uni.setStorageSync('memberInfo', {
              name: this.name,
              phone: this.phone,
              member_discount: 500
            })
            
            uni.hideLoading()
            uni.showToast({ title: '登录成功', icon: 'success' })
            
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/member/member'
              })
            }, 1500)
          } catch (err) {
            uni.hideLoading()
            uni.showToast({ title: '登录失败', icon: 'none' })
          }
        },
        fail: () => {
          uni.showToast({ title: '微信授权失败', icon: 'none' })
        }
      })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 40rpx;
}

.header {
  text-align: center;
  margin-bottom: 60rpx;
  margin-top: 80rpx;
}

.title {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.subtitle {
  display: block;
  font-size: 28rpx;
  color: #999;
}

.form {
  background: white;
  padding: 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 20rpx rgba(0,0,0,0.1);
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.input {
  padding: 20rpx;
  background: #f5f5f5;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.btn {
  margin-top: 30rpx;
}
</style>

